package cn.sh.basic.util;

import cn.sh.basic.jwt.JwtUtils;
import cn.sh.basic.jwt.Payload;
import cn.sh.basic.jwt.RsaUtils;
import cn.sh.basic.jwt.UserInfo;
import cn.sh.user.domain.Logininfo;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.PublicKey;

public class LoginContextUtils {
    public static Logininfo getCurrentUser(HttpServletRequest request) {
        try {
            String token = request.getHeader("U-TOKEN");
            //通过获取的token去redis中查询
//            Object loginInfo = redisTemplate.opsForValue().get(token);
            //获取公钥
            PublicKey publicKeyPath = RsaUtils
                    .getPublicKey(FileCopyUtils
                            .copyToByteArray(LoginContextUtils.class.getClassLoader().getResourceAsStream("hrm_auth_rsa.pub")));
            //获取载荷数据
            Payload<UserInfo> payLoad = JwtUtils.getInfoFromToken(token, publicKeyPath, UserInfo.class);
            //从载荷数据中获取用户信息
            UserInfo userInfo = payLoad.getUserInfo();
           /* //从userinfo中获取用户登录信息
            Logininfo loginInfo = userInfo.getLogininfo();*/
            return userInfo.getLogininfo();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
